/**
 * Controller
 */
const News = require("../models/news");
const CommonResult = require("../common/commonResult");
const PageResult = require("../common/pageResult");
const PageInfo = require("../common/pageInfo");

/**
 * 分页查询
 * @param {Object} ctx
 */
async function pageList(ctx) {
  // ctx.request.body post 请求的参数在body中
  let { page = 1, size = 10 } = ctx.request.body;

  let query = News.find({});
  let conditions = {};

  // 每页大小
  query.skip((page - 1) * size);
  query.limit(size);
  try {
    // 计算分页数据
    const lists = await query.exec();

    // 计算数据总数
    const result = await News.find(conditions);
    const totalPage = Math.ceil(result.length / size);
    const totalSize = result.length;

    const pageInfo = new PageInfo(
      page === 1,
      page === totalPage,
      page,
      size,
      totalPage,
      totalSize
    );
    const pageResult = new PageResult(200, "查询成功", lists, pageInfo);

    ctx.body = pageResult;
  } catch (e) {
    const pageResult = new PageResult(5000, "查询失败", [], {});
    ctx.body = pageResult;
  }
}

/**
 * 新增
 * @param {Object} ctx
 */
async function add(ctx) {
  // ctx.request.body 获取post请求的参数
  let {
    author = "admin",
    html,
    title,
    url,
  } = ctx.request.body;
  if (!title || !html) {
    ctx.body = new CommonResult(4000, "内容不能为空", null);
    return;
  }
  
  let news = await News.create({
    author,
    html,
    url,
    title,
  });

  if (news) {
    ctx.body = new CommonResult(200, "创建成功", news);
  } else {
    ctx.body == new CommonResult(500, "创建失败", null);
  }
}

async function edit(ctx) {
  let { id, author, html, title, url } = ctx.request.body;
  if (!id || !title || !html) {
    ctx.body = new CommonResult(4000, "id、标题、内容不能为空", null);
    return;
  }
  let news = await News.findByIdAndUpdate(id, {
    author,
    html,
    title,
    url,
  });
  if (news) {
    ctx.body = new CommonResult(200, "编辑成功", news);
  } else {
    ctx.body = new CommonResult(500, "编辑失败", null);
  } 
}


/**
 * 删除
 * @param {Object} ctx
 */
async function del(ctx) {
  // ctx.request.body 获取post请求的参数
  let { id } = ctx.request.body;
  if (!id) {
    ctx.body = new CommonResult(4000, "id不能为空", null);
    return;
  }
  let news = await News.findOneAndDelete({'_id': id});
  if (news) {
    ctx.body = new CommonResult(200, "删除成功", news);
  } else {
    ctx.body = new CommonResult(500, "删除失败", null);
  }

}

async function detail(ctx) {
  let { id } = ctx.request.body;
  if (!id) {
    ctx.body = new CommonResult(4000, "id不能为空", null);
    return;
  }
  let news = await News.findById(id);
  if (news) {
    ctx.body = new CommonResult(200, "查询成功", news);
  } else {
    ctx.body = new CommonResult(500, "查询失败", null);
  }
}

async function idList(ctx) {
  let news = await News.find({}, { id: 1 });
  if (news) {
    ctx.body = new CommonResult(200, "查询成功", news);
  } else {
    ctx.body = new CommonResult(500, "查询失败", null);
  }
}


module.exports = { pageList, add, del, detail, edit, idList };
